package com.roger.ndtplayer.base

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.roger.ndtplayer.commom.USER_LOGIN_STATE
import com.roger.ndtplayer.commom.core.MMKVHelper
import com.roger.ndtplayer.commom.dialog.ProgressDialogFragment
import com.tencent.mmkv.MMKV


/**
 * A simple [Fragment] subclass.
 */
abstract class BaseFragment : Fragment() {

    private lateinit var progressDialogFragment: ProgressDialogFragment
    val myMMKVa: MMKV by lazy { MMKV.defaultMMKV() }
    abstract val layoutId: Int

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initView()
        super.onViewCreated(view, savedInstanceState)
        initData()
    }

    /**
     * View初始化相关
     */
    open fun initView() {
        // Override if need
    }

    /**
     * 数据初始化相关
     */
    open fun initData() {
        // Override if need
    }
    /**
     * 懒加载数据
     */
    open fun lazyLoadData() {
        // Override if need
    }

    /**
     * 是否登录，如果登录了就执行then，没有登录就直接跳转登录界面
     * @return true-已登录，false-未登录
     */
    fun checkLogin(then: (() -> Unit)? = null): Boolean {
        return if (MMKVHelper.getMMKVValue(USER_LOGIN_STATE,false)) {
            then?.invoke()
            true
        } else {
//            ActivityHelper.startActivity(LoginActivity::class.java)
            false
        }
    }

    /**
     * 显示加载(转圈)对话框
     */
    fun showProgressDialog(message: String) {
        if (!this::progressDialogFragment.isInitialized) {
            progressDialogFragment = ProgressDialogFragment.newInstance()
        }
        if (!progressDialogFragment.isAdded) {
            progressDialogFragment.showDialog(parentFragmentManager, message)
        }
    }

    /**
     * 隐藏加载(转圈)对话框
     */
    fun dismissProgressDialog() {
        if (this::progressDialogFragment.isInitialized && progressDialogFragment.isVisible) {
            progressDialogFragment.dismissAllowingStateLoss()
        }
    }
}
